import 'dart:js_interop_unsafe';

import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_small_project/utils/Toast.dart';
import 'package:flutter_small_project/utils/tokenManager.dart';

import '../../api/user.dart';
import '../../utils/eventBus.dart';

class MinePage extends StatefulWidget {
  const MinePage(
      {super.key,
      required this.currentIndex,
      required this.changreActiveIndex});
  final int currentIndex;
  final Function(int) changreActiveIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 创建变量接收用户信息
  Map userInfo = {
    "id": '',
    "avatar": '',
    "nickName": '',
  };
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    eventBus.on<LoginEvent>().listen((event) {
      getUserInfo();
    });

    eventBus.on<LogSuccessEvent>().listen((event) {
      print(event.message);
      // 获取用户信息
     getUserInfo();
    });
  }

  @override
  didUpdateWidget(MinePage oldWidget) {
    if (widget.currentIndex == 1) {
      PromptAction.showInfo('欢迎来到我的页面');
      // 发送请求获取用户信息
      getUserInfo();
    }
  }

  getUserInfo() async {
    final res = await getUserInfoAPI();
    // print(res);
    setState(() {
      userInfo = res;
    });
    print(userInfo);
  }

  List<Widget> getTitleChild() {
    return [
      ClipRRect(
        borderRadius: BorderRadius.circular(50.0),
        child: userInfo['avatar'] != null && userInfo['avatar'] != ''
            ? Image.network(userInfo['avatar'], width: 50, height: 50)
            : Image.asset(
                'assets/images/avatar_1.jpg',
                width: 50,
                height: 50,
              ),
      ),
      const SizedBox(width: 10),
      Text(
          userInfo['nickName'] != null && userInfo['nickName'] != ''
              ? userInfo['nickName']
              : '用户名',
          style: const TextStyle(fontSize: 16, color: Colors.white)),
      const Spacer(),
      GestureDetector(
        onTap: () {
          // 跳转到个人资料页面 并携带用户信息
          Navigator.pushNamed(context, '/profile', arguments: userInfo);
        },
        child: const Row(
          children: [
            Text(
              '去完善信息',
              style: TextStyle(color: Colors.white),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: Colors.white,
              size: 13,
            )
          ],
        ),
      )
    ];
  }

  List<Widget> getChildren() {
    return menuList
        .map(
          (item) => SizedBox(
            height: 50,
            child: Row(
              children: [
                Row(
                  children: [
                    Image.asset(
                      item['icon'],
                      width: 20,
                      height: 20,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text(
                      item['title'],
                      style: const TextStyle(fontSize: 16),
                    )
                  ],
                ),
                const Spacer(),
                const Icon(
                  Icons.arrow_forward_ios,
                  size: 12,
                  color: Colors.grey,
                )
              ],
            ),
          ),
        )
        .toList();
  }

  // 点击退出登录时,跳出弹窗
  void _loyout() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: const Text('温馨提示'),
              content: const Text('确定要退出登录吗?'),
              actions: [
                TextButton(
                  onPressed: () {
                    // 点击取消时,只需要关闭弹窗
                    // pop() 方法,使用场景 1.关闭弹窗 2.返回上一个页面
                    Navigator.pop(context);
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    // 首先应该删除token + refreshToken
                    tokenManager.deleteToken();
                    // 重置用户信息
                    setState(() {
                      userInfo = {
                        'id': '',
                        'avatar': '',
                        'username': '',
                      };
                    });
                    // 跳转到首页
                    //[问题]:通过下标,使其页面跳转到首页
                    //[bug]:如果使用Navigator.pushNamed(context, '/')进行跳转,会让使底部的导航栏不会跟着跳转
                    //[解决]:在父组件中创建一个方法,然后传递给子组件,在子组件中调用父组件的方法
                    widget.changreActiveIndex(0);
                    // 关闭弹窗
                    Navigator.pop(context);
                  },
                  child: const Text('确定'),
                )
              ]);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                // Navigator.pushNamed(context, '/profile');
              },
              child: Row(
                children: getTitleChild(),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: getChildren(),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                _loyout();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color.fromRGBO(255, 222, 14, 14),
              ),
              child: const Text(
                '退出登录',
                style: TextStyle(color: Colors.white),
              ),
            ),
          )
        ],
      ),
    );
  }
}
